package com.cqc.jdk8.Jutil.stream;

import com.cqc.eb.UserEB;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ForeachTest {


    List<UserEB> userEBList = null;
    Map<String, UserEB> userMap = null;

    @Before
    public void before() {
        userEBList = getUserEBList();
        userMap = getUserMap();
    }

    /**
     * 遍历并跳过前3个
     */
    @Test
    public void skipLimit() {
        String[] arr = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
        int pageSize = 2;
        int count = (arr.length % pageSize == 0) ? (arr.length / pageSize) : (arr.length / pageSize + 1);
        for (int i = 0; i < count; i++) {
            List<String> list = Stream.of(arr)
                    .skip(i * pageSize)
                    .limit(pageSize)
                    .collect(Collectors.toList());
            System.out.println("i=" + i + "  " + list);
        }
    }

    /**
     * forEach 会改变原有的对象
     */
    @Test
    public void forEach() {
        userEBList.stream()
                .forEach(user -> user.setAge(user.getAge() + 10));

        userEBList.stream()
                .forEach(System.out::println);
        //所有人的年龄大了10岁
    }

    @Test
    public void mapForEach() {
        userMap.entrySet()
                .forEach(System.out::println);
    }


    private List<UserEB> getUserEBList() {
        userEBList = new ArrayList<>();
        userEBList.add(new UserEB("刘诗诗", 30));
        userEBList.add(new UserEB("刘亦菲", 31));
        userEBList.add(new UserEB("古力娜扎", 28));
        return userEBList;
    }

    private Map<String, UserEB> getUserMap() {
        userMap = new HashMap<>(16);
        userMap.put("1", new UserEB("刘诗诗", 33));
        userMap.put("2", new UserEB("刘亦菲", 33));
        userMap.put("3", new UserEB("古力娜扎", 30));
        return userMap;
    }
}
